package JDBC;

import utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/*
* 练习
* 登录案列 */
public class jdbcdemo05 {
    public static void main(String[] args) {
        //键盘输入用户名和密码
        Scanner sc= new Scanner(System.in);
        System.out.println("请输入用户名");
        String username = sc.nextLine();
        System.out.println("请输入密码");
        String password = sc.nextLine();
        // 调用方法
        boolean flag= new jdbcdemo05().login(username,password);
         //判断结果
        if (flag=true){
            System.out.println("登陆成功");
        }else {
            System.out.println("登录失败,请确认后再次登录");
        }
    }
    /*
    * 登录方法  使用的是prepareStatement
    * */

    public boolean login(String username, String password){
        if (username == null || password == null ) {
            return false;
        }
        //连接数据库判断其是否登录成功
        Connection conn = null;
        PreparedStatement  pstmt = null;
        ResultSet rs = null;


        try {
            //获取连接
           conn = JDBCUtils.ConnectionUtils();
            //定义sql
            String sql = "select * from user where username = ? and password = ? ";
            //获取执行sql对象
           pstmt = conn.prepareStatement(sql);
           //给 ?  赋值
            pstmt.setString(1, username);
            pstmt.setString(2, password);
           // 执行查询,不需要传递sql
             rs = pstmt.executeQuery();
             // 判断,如果有下一行则返回true
            return rs.next(); //如果有下一行,则会返回true

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.Close(rs,pstmt,conn);


        return false;
        }

    }
}
